package com.example.ai.page

import android.app.Activity
import android.graphics.Rect
import android.os.Build
import android.view.ViewTreeObserver
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.isImeVisible
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.rememberAsyncImagePainter
import com.example.ai.Config
import com.example.ai.model.data.Identity
import com.example.ai.model.viewmodel.MessageViewModel
import com.example.ai.view.MessageInput
import com.example.ai.view.MessageItem
import com.example.ai.view.VideoPlayContent
import kotlinx.coroutines.isActive

/**
 * Created by lijinxi on 2024/3/9.
 * @Description:
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun VideoChatPage(title: String, viewModel: MessageViewModel) {
    LocalView.current
    val context = LocalContext.current
    val listState = rememberLazyListState()

    val rotation = remember { Animatable(0f) }

    LaunchedEffect(Unit) {
        while (true) {
            rotation.animateTo(
                targetValue = rotation.value + 360f,
                animationSpec = tween(durationMillis = 30_000, easing = LinearEasing)
            )
        }
    }

    val consumeList by remember {
        derivedStateOf {
            mutableStateListOf<Pair<Int, String>>().apply {
                viewModel.messages.forEachIndexed { index, messageData ->
                    if (messageData.identity == Identity.OTHER && messageData.talkUrl != null && !messageData.consumed) {
                        val pair = Pair(index, messageData.talkUrl)
                        if (this.contains(pair).not()) this.add(pair)
                    }
                }
            }
        }
    }

    LaunchedEffect(key1 = viewModel.messages.size) {
        val index = viewModel.messages.size - 1
        if (index >= 0) {
            listState.scrollToItem(index)
        }
    }

    BackHandler {
        (context as? Activity)?.finish()
    }

    Column(modifier = Modifier.fillMaxSize()) {
        //顶部标题

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp)
                .align(Alignment.CenterHorizontally),
            horizontalArrangement = Arrangement.Center
        ) {
            Text(
                text = title,
                color = Color.Black,
                style = TextStyle(
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold
                ),
            )
        }

        //视频区域
        Row(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .align(Alignment.CenterHorizontally)
                .padding(horizontal = 16.dp, vertical = 32.dp),
            horizontalArrangement = Arrangement.Center
            /*
            .layout { measurable, constraints ->
                val placeable = measurable.measure(constraints)
                layout(constraints.maxWidth, constraints.maxHeight) {
                    val top = (constraints.maxHeight - placeable.height) / 2 - 200
                    val left = (constraints.maxWidth - placeable.width) / 2
                    placeable.placeRelative(left, top)
                }
            }*/
        ) {
            if (consumeList.size > 0) {
                VideoPlayContent(consumeList, viewModel)
            } else {
                val painter = rememberAsyncImagePainter(
                    model = Config.AVATAR
                )
                /*
                Image(
                    painter = painter,
                    contentDescription = "头像",
                    modifier = Modifier
                        .size(200.dp)
                        .clip(CircleShape)
                        .rotate(rotation.value)
                        .align(Alignment.CenterVertically),
                    contentScale = ContentScale.Fit
                )*/
                Image(
                    painter = painter,
                    contentDescription = "头像",
                    modifier = Modifier
                        .fillMaxWidth()
                        //.clip(CircleShape)
                        //.rotate(rotation.value)
                        .clip(RoundedCornerShape(16.dp))
                        .align(Alignment.CenterVertically),
                    contentScale = ContentScale.Crop
                )
            }
        }

        //聊天浮层
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceAround
        ) {
            Column {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(300.dp)
                ) {
                    LazyColumn(state = listState) {
                        itemsIndexed(viewModel.messages) { index, item ->
                            MessageItem(
                                messageData = item,
                                index = index,
                                loadAudioUrl = { _index ->
                                    viewModel.fetchVoice(_index)
                                },
                                hasAudioIcon = false,
                                loadTalkId = { _index ->
                                    viewModel.fetchTalkId(_index)
                                },
                                loadTalkUrl = { _index ->
                                    viewModel.fetchTalkUrl(_index)
                                }
                            )
                        }
                    }
                }
                HorizontalDivider(
                    modifier = Modifier.padding(top = 16.dp),
                    color = Color.Transparent
                )
                Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.BottomCenter) {
                    MessageInput(
                        onSendMessage = { text ->
                            viewModel.sendMessage(text)
                        },
                        onPhoneCall = {
                        },
                        hasPhoneCall = false
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun imeVisible(): State<Boolean> {
    val isImeVisible = remember { mutableStateOf(false) }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        isImeVisible.value = WindowInsets.isImeVisible
    } else {
        val view = LocalView.current
        DisposableEffect(view) {
            val onGlobalListener = ViewTreeObserver.OnGlobalLayoutListener {
                val rect = Rect()
                view.getWindowVisibleDisplayFrame(rect)
                val screenHeight = view.rootView.height
                val keypadHeight = screenHeight - rect.bottom
                isImeVisible.value = keypadHeight > screenHeight * 0.15
            }
            view.viewTreeObserver.addOnGlobalLayoutListener(onGlobalListener)
            onDispose {
                view.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalListener)
            }
        }
    }

    return isImeVisible
}